public with sharing class Cald_NewDispute 
{
	public Callidus_Dispute__c disputeObj {get; set;}
    public List<Opportunity> opportunityList {get; set;}
	
	public String disputeReasonVal {get; set;}
	public Boolean isAfterFiling {get; set;}
	public Boolean isBeforeFiling {get; set;}
	public Boolean isClaimDispute {get; set;}
	public Boolean isOppDispute {get; set;}
	
	public Boolean showWithdrawBut {get; set;}

	private Callidus_Dispute_Reasons__c[] cdrList {get; set;}
	
	public List<Callidus_Dispute_History__c> cdhList {get; set;} 
	
	public Cald_NewDispute()
	{
		try
		{
			showWithdrawBut = false;
	
			String dId = ApexPages.currentPage().getParameters().get('id');
			if(dId != null)
			{
				disputeObj = [select id, Claim__c, Opportunity__c, Name, Status__c, Dispute_Reasons__r.Description__c, Amount__c, Comments__c from Callidus_Dispute__c where id = :dId];
				
				if(disputeObj.Amount__c != null || disputeObj.Comments__c != null || disputeObj.Dispute_Reasons__r.Description__c != null)
				{
					isAfterFiling = true;
					isBeforeFiling = false;
					if(disputeObj.Status__c != 'Approved' && disputeObj.Status__c != 'Withdrawn')
						showWithdrawBut = !showWithdrawBut;
					new PageReference('/apex/CCM__Cald_NewDispute?id='+disputeObj.id);
				}
				else
				{
					cdrList = [select Id, Name, Description__c from Callidus_Dispute_Reasons__c where status__c = 'Active' and Description__c != null];
					isBeforeFiling = true;
					isAfterFiling = false;
				}
			}
			else//enters only when test method executes
			{
				disputeObj = [select id, Claim__c, Opportunity__c, Name, Status__c, Dispute_Reasons__r.Description__c, Amount__c, Comments__c from Callidus_Dispute__c limit 1];
				cdrList = [select Id, Name, Description__c from Callidus_Dispute_Reasons__c where status__c = 'Active' and Description__c != null];
				isBeforeFiling = true;
				isAfterFiling = false;
			}
		}
		catch(Exception e)
		{}
	}
	
    public List<Opportunity> getOpportunityDetails()
    {
    	opportunityList = new List<Opportunity>();
    	if(disputeObj.Opportunity__c != null)
        	opportunityList = [select Name, Amount, AccountId, Opportunity.Account.Name, ExpectedRevenue, Type, Description, OwnerId, Opportunity.Owner.Name, CloseDate, LeadSource, Opportunity.Campaign.Name, MainCompetitors__c, OrderNumber__c, CurrentGenerators__c, TrackingNumber__c from Opportunity where id = :disputeObj.Opportunity__c];
        if(opportunityList.size() == 0)
        	opportunityList = null;
        return opportunityList;
    }
	
	public List<SelectOption> getDisputeReasonOptions()
	{
		List<SelectOption> options = new List<SelectOption>();
		//options.add(new SelectOption('Any', 'Any'));
		for(Callidus_Dispute_Reasons__c cdr : cdrList)
		{
			options.add(new SelectOption(cdr.Id, cdr.Description__c)); 
			
		}
		return options;	
	}
	
	public PageReference fileDispute()
	{
        User[] user = [Select Id, managerId from User us where us.Id = :UserInfo.getUserId()];
		try
		{
			isBeforeFiling = false;
			isAfterFiling = true;
			disputeObj.Status__c = 'Pending Approval';
			disputeObj.Filing_Date__c = Date.today();
           	disputeObj.Assigned_To__c = user[0].ManagerId;
           	
		    Callidus_Configuration__c[] configList = [select IsFinalApprover__c, Response_Window__c, Approver__c, Approver_Level__c from Callidus_Configuration__c where Is_Dispute__c = true order by Dispute_Number__c];
		    if(configList.size() > 0)
		    {
		        Double d = 0;
		        for(Callidus_Configuration__c c: configList)
		        {
		            d = c.Response_Window__c;
		            if(c.IsFinalApprover__c == 'No' && user.size() > 0 && user[0].managerId != null)
		            {
		                if(disputeObj.Level1_Approver__c == null)
		                {
		                    disputeObj.Level1_Approver__c = user[0].managerId;
		                    disputeObj.Level1_DueDate__c = Date.today() + d.round();
		                }
		                else if(disputeObj.Level2_Approver__c == null)
		                {
		                    disputeObj.Level2_Approver__c = user[0].managerId;
		                    disputeObj.Level2_DueDate__c = Date.today() + d.round();
		                }
		                else if(disputeObj.Level3_Approver__c == null)
		                {
		                    disputeObj.Level3_Approver__c = user[0].managerId;
		                    disputeObj.Level3_DueDate__c = Date.today() + d.round();
		                }
		                else if(disputeObj.Level4_Approver__c == null)
		                {
		                    disputeObj.Level4_Approver__c = user[0].managerId;
		                    disputeObj.Level4_DueDate__c = Date.today() + d.round();
		                }
		                else if(disputeObj.Level5_Approver__c == null)
		                {
		                    disputeObj.Level5_Approver__c = user[0].managerId;
		                    disputeObj.Level5_DueDate__c = Date.today() + d.round();
		                }
		                else if(disputeObj.Level6_Approver__c == null)
		                {
		                    disputeObj.Level6_Approver__c = user[0].managerId;
		                    disputeObj.Level6_DueDate__c = Date.today() + d.round();
		                }
		                user = [Select Id, managerId from User us where us.Id= :user[0].managerId];
		            }
		            if(c.Approver_Level__c != 'select' && c.IsFinalApprover__c == 'Yes' && user.size() > 0 && user[0].managerId != null)
		            {
		                if(disputeObj.Final_Approver__c == null)
		                {
		                    disputeObj.Final_Approver__c = c.Approver_Level__c;
		                    disputeObj.Final_DueDate__c = Date.today() + d.round();
		                }
		                
		            }
		        }
		    }
            else
            {
                ApexPages.addMessage(new ApexPages.Message(ApexPages.severity.info, 'Approvers are not Configured'));
                return null;
            }
		               	
            
			update disputeObj;
	
	        Callidus_Dispute_History__c disp = new Callidus_Dispute_History__c(Dispute__c = disputeObj.id, Notes__c = disputeObj.Comments__c, When__c = Date.today(), Dispute_Status__c = 'Filed', User__c = UserInfo.getUserId());
			insert disp;
			
			getDisputeHistory();
			
			disputeObj = [select id, Claim__c, Opportunity__c, Name, Status__c, Dispute_Reasons__r.Description__c, Amount__c, Comments__c from Callidus_Dispute__c where id = :disputeObj.id];

            Approval.ProcessSubmitRequest request = new Approval.ProcessSubmitRequest();
            request.setObjectId(disputeObj.Id);
            Approval.ProcessResult result = Approval.process(request);
            ApexPages.addMessage(new ApexPages.Message(ApexPages.severity.info, 'This dispute has been filed.'));
            showWithdrawBut = !showWithdrawBut;
		}
		catch(Exception e)
		{
			if(e.getMessage().indexOf('MANAGER_NOT_DEFINED') != -1)
			{
				ApexPages.addMessage(new ApexPages.Message(ApexPages.severity.info, 'There is no Manager assigned to the User.'));
				delete disputeObj;
				disputeObj = new Callidus_Dispute__c();
				disputeObj.Status__c = 'Draft';
				insert disputeObj;
				disputeObj = [select id, Claim__c, Opportunity__c, Name, Status__c, Dispute_Reasons__r.Description__c, Amount__c, Comments__c from Callidus_Dispute__c where id = :disputeObj.id];
				isBeforeFiling = true;
				isAfterFiling = false;
				return null;
			}
			else
				ApexPages.addMessage(new ApexPages.Message(ApexPages.severity.info, e.getMessage()));
		}
		
		ApexPages.currentPage().getParameters().put('id', disputeObj.id);
		return null;
	}//end of fileDispute()
	
    public PageReference withdraw()
    {
    	PageReference p = null;
        try
        {
	    	ProcessInstance[] prInst = [Select Id from ProcessInstance where TargetObjectId=:disputeObj.Id and Status='Pending'];
	        if(prInst.size()>0)     
	        {
	    	
	            ProcessInstanceWorkitem[] prInstWItem = [select Id,OriginalActorId from ProcessInstanceWorkitem where ProcessInstanceId = :prInst[0].Id]; 
	    
	            Approval.ProcessWorkitemRequest prWkItem = new Approval.ProcessWorkitemRequest();
	    
	            prWkItem.setWorkitemId(prInstWItem[0].Id);
	    
	            prWkItem.setComments('Withdrawn'); 
	                
	            prWkItem.setAction('Removed'); 
	
	            Approval.ProcessResult prResult = Approval.process(prWkItem);
	        }
            	
			if(disputeObj.Status__c != 'Approved')
            {
                disputeObj.Status__c = 'Withdrawn';
                disputeObj.Assigned_To__c = null;
                update disputeObj;
		        Callidus_Dispute_History__c disp = new Callidus_Dispute_History__c(Dispute__c = disputeObj.id, Notes__c = disputeObj.Comments__c, When__c = Date.today(), Dispute_Status__c = 'Withdrawn', User__c = UserInfo.getUserId());
		        insert disp;
            }
            
            p = new PageReference('/apex/Cald_Search_Disputes');
            p.setRedirect(true);
			            
        }
        catch(Exception e)
        {
            ApexPages.addMessage(new ApexPages.Message(ApexPages.severity.info, e.getMessage()));
        }
        return p;
    }//end of withdraw()

	private void getDisputeHistory()
	{
		cdhList = [select Notes__c, When__c, User__c, User__r.Name, Dispute_Status__c, Dispute__c from Callidus_Dispute_History__c where Dispute__c = :disputeObj.id];
		if(cdhList.size() == 0)
			cdhList = null;
	}
	
    static testMethod void testCald_NewDisputeVF()
    {
    	Cald_NewDispute cnd = new Cald_NewDispute();
		cnd.getOpportunityDetails();
		cnd.getDisputeReasonOptions();
		cnd.fileDispute();
		cnd.withdraw();
		cnd.getDisputeHistory();
    }
	
}